package com.gold.common;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

import java.io.IOException;

/**
 * @author XiaoHao
 * @date 2022-06-01 09:24
 */
public class HttpUtils {

    /**
     * post 请求
     * @param url
     * @param param
     * @return
     */
    public static JSONObject doPost(String url, String param) {
        //获得http客户端
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        //创建post请求
        HttpPost httpPost = new HttpPost(url);
        httpPost.setHeader("Content-Type", "application/json;charset=utf8");
        httpPost.setEntity(new StringEntity(param, "UTF-8"));
        //由客户端执行发送post请求
        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            if (response.getStatusLine() != null) {
                //将返回数据转为json
                String string = EntityUtils.toString(entity);
                if (StringUtils.isNotEmpty(string)){
                    JSONObject jsonObject = JSON.parseObject(string);
                    return jsonObject;
                }
            } else {
                System.out.println(response.getStatusLine());
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (httpClient != null) {
                    httpClient.close();
                }
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}

